(function(TabControl, $) {
  TabControl.setupTabs = function() {
    var $pages = $('div#tab_control .pages .page');

    if($pages.length > 0) {
      TabControl.updateTabsBasedOnPages();

      $('div#tab_control .tabs').on('click', '.tab', function(event) {
        event.preventDefault();
        TabControl.selectTab($(this).attr('id'));
      });

      $('div#tab_control .tabs').on('click', '.tab .close', function(event) {
        event.stopPropagation();
        TabControl.removeTab($(this).closest('.tab').attr('id'));
      });

      TabControl.selectTab($pages.first().attr('id').replace(/-/, "_"));
    }
  }

    TabControl.selectTab = function(id) {
        id = id.replace(/^tab_/, '').replace(/^page_/, '');
        var underscored_id = id.replace(/_/g, "-").toLowerCase();
        var $pages = $('div#tab_control .pages .page');
        var $tabs  = $('div#tab_control .tabs .tab');

        $pages.hide();
        $tabs.removeClass('here');

        $pages.filter('#page_' + underscored_id).show();
        $tabs.filter('#tab_' + id).addClass('here');
    }

  TabControl.addTab = function(tabText) {
    $('div#tab_control .tabs').append("<a id='tab_" + tabText + "' href='#' class='tab'><span>" + tabText + "</span><img src='" + relative_url_root + "<%= asset_path('admin/tab_close.png') %>' class='close' alt='Remove part' title='Remove part' /></a>");
    var $page_part_index = $('#page_part_index_field');
    $page_part_index.val(parseInt($page_part_index.val()) + 1);
  }

  TabControl.removeTab = function(id) {
    id = id.replace(/^tab_/, '').replace(/^page_/, '').toLowerCase();
    var underscored_id = id.replace("_", "-").toLowerCase();
    if(confirm('Remove the "' + id + '" part?')) {
      var $pages = $('div#tab_control .pages .page');
      var $tabs  = $('div#tab_control .tabs .tab');

      var $tab = $tabs.filter('#tab_' + id);
      if($tab.hasClass('here')) {
        var $prevTab = $tab.prev('.tab');
        var $nextTab = $tab.next('.tab');
        if($prevTab.length > 0) {
          TabControl.selectTab($prevTab.attr('id'));
        } else if($nextTab.length > 0) {
          TabControl.selectTab($nextTab.attr('id'));
        }
      }
      $tab.remove();

      $page = $pages.filter('#page_' + underscored_id);
      var idInput = $page.find('.id_input');
      var deleteInput = $page.find('.delete_input');
      deleteInput.attr('value', 'true');
      $('div#tab_control').append(idInput).append(deleteInput);
      $page.remove();
    }
  }

  TabControl.updateTabsBasedOnPages = function() {
    var $pages = $('div#tab_control .pages .page');
    $pages.each(function(page) {
      var tabName = $(this).data('caption');
      if($('div#tab_control .tabs #tab_' + tabName).length == 0) {
        TabControl.addTab($(this).data('caption'));
      }
    });
  }

}(window.TabControl = window.TabControl || {}, jQuery));

$(function () {
  TabControl.setupTabs();
});
